<?php

namespace App\Http\Requests\Admin;

use App\Rules\IdCard;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class UserRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        switch ($this->method()) {
            case 'POST':
                return [
                    'username' => 'required|string|min:2|max:22|unique:users,username',
                    'name' => 'required|string|min:2|max:22',
                    'email' => 'required|email|unique:users,email',
                    'phone' => ['sometimes', 'nullable', 'regex:/^1(?:(?:(?:3|5|7|8)[0-9])|47|6[89]|99)\d{8}$/'],
                    'id_card' => ['sometimes', 'nullable', new IdCard(), 'unique:users,id_card'],
                    'roles' => ['sometimes', 'nullable', 'array', 'exists:roles,id'],
                    'section' => ['sometimes', 'nullable', 'array', 'exists:sections,id'],
                    'password' => 'required|min:6|max:32|'
                ];
            case 'PUT':
                return [
                    'id' => 'required|numeric|exists:users,id',
                    'username' => ['sometimes', 'required', 'string', 'between:2,22', Rule::unique('users', 'username')->ignore(request()->input('id'))],
                    'name' => ['sometimes', 'required', 'string'],
                    'email' => ['sometimes', 'required', 'email', Rule::unique('users', 'email')->ignore(request()->input('id'))],
                    'phone' => ['sometimes', 'nullable', 'regex:/^1(?:(?:(?:3|5|7|8)[0-9])|47|6[89]|99)\d{8}$/'],
                    'roles' => ['sometimes', 'nullable', 'array', 'exists:roles,id'],
                    'section' => ['sometimes', 'nullable', 'array', 'exists:sections,id'],
                ];
        }
    }

    public function attributes()
    {
        return [
            'username' => '登录名',
            'name' => '用户名',
            'email' => '邮箱',
            'phone' => '手机号',
            'id_card' => '身份证',
            'roles' => '角色'
        ];
    }
}
